<template>
  <div>
    <SearchBar :option="searchProps" @search="handleSearch"/>
    <el-table :data="list" :loading="loading" class="mt20">
      <el-table-column label="名称" prop="lockAlias"></el-table-column>
      <el-table-column label="锁编号" prop="lockName">
        <template #default="{ row }">{{ row.lockInfoObj.lockName }}%</template>
      </el-table-column>
<!--      <el-table-column label="类型" prop="type" width="100px"></el-table-column>-->
      <el-table-column label="电量" prop="electricQuantity" width="100px">
        <template #default="{ row }">
          <el-tag :type="row.lockInfoObj.electricQuantity && row.lockInfoObj.electricQuantity < 10 ? 'danger' : 'success'">
            {{ row.lockInfoObj.electricQuantity }} %
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="电量更新时间" prop="electricQuantityUpdateDate">
        <template #default="{ row }">
          <div class="flex-row-center">
            <span>{{ parseTime(row.lockInfoObj.lockUpdateDate) }}</span>
            <el-icon @click="syncLockInfo(row)" color="var(--el-color-primary)" size="20"><RefreshRight /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="绑定网关" prop="hasGateway" width="80px">
        <template #default="{ row }">{{ row.lockInfoObj.hasGateway === 1 ? '是' : '否' }}</template>
      </el-table-column>
      <el-table-column label="关联房间" prop="chamberNum">
        <template #default="{ row }">
          <el-button v-if="row.roomId && row.roomId !== -1 && row.roomId !== ''" link type="primary" @click="associationRoom(row)">{{ row.roomName }}</el-button>
          <el-button v-else link type="primary" @click="toAssociationRoom(row)">去关联</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
          <el-button link type="primary" @click="handleUnLock(row)">远程开门</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <LockEdit ref="lockEditRef" :row="row" />
    <AssociationRoomDrawer
      ref="associationRoomRef"
      :visible="accociation.visible"
      :deviceType="accociation.deviceType"
      :is-public="accociation.isPublic"
      :data="accociation.data"
      :total="accociation.total"
      v-model:page="accociation.pageNum"
      v-model:limit="accociation.pageSize"
      @pagination="handleGetAssociationList"
      @unbind="unbindRoom"
      @cancel="() => accociation.visible = false"
    />
    <UnAssociationRoomDrawer
        :visible="unAssociationRoomVisible"
        v-if="row.lockId && row.lockId !== ''"
        :lock-id="row.lockId"
        @bind-complete="bindComplete"
        @cancel="() => unAssociationRoomVisible = false"
    />
  </div>
</template>
<script setup name="SmartLock">
import LockEdit from './lockEdit.vue'
import AssociationRoomDrawer from '../component/associationRoomDrawer.vue'
import SearchBar from '../component/searchBar.vue'
import { useRouter } from 'vue-router'
import {getList as getLockList, syncLock, unlock} from "@/api/device/lock.js";
import {Bell, WarningFilled} from "@element-plus/icons-vue";
import LockApi from "@/api/device/lock.js";
import UnAssociationRoomDrawer from "@/views/deviceManagement/component/unAssociationRoomDrawer.vue";

const { proxy } = getCurrentInstance()
const router = useRouter()

const loading = ref(false)
const total = ref(0)
const list = ref([])
const row = ref({})
const unAssociationRoomVisible = ref(false)
const searchProps = ref({
  group: false,
  smartLockType: true,
  searchStr: {
    show: true,
    key: 'searchStr',
    placeholder: '请输入锁名称或房源地址'
  }
})
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  accociation: {
    deviceType: 1,
    isPublic: false,
    data: [],
    total: 0,
    pageNum: 1,
    pageSize: 20,
    visible: false
  }
})
const { queryParams, accociation } = toRefs(data)

/* 搜索 */
function handleSearch(params) {
  queryParams.value = { ...queryParams.value, ...params }
  console.log(queryParams.value)
  getList()
}

/* 编辑锁 */
function handleEdit(row) {
  row.value = { ...row }
  proxy.$refs['lockEditRef'].show()
  getList()
}

function syncLockInfo(row) {
  syncLock(row.lockId).then(res => {
    proxy.$message.success('操作成功')
    getList()
  })
}

function toAssociationRoom(item) {
  row.value = item
  unAssociationRoomVisible.value = true
}

// 绑定门锁完成
function bindComplete() {
  unAssociationRoomVisible.value = false
  getList()
}

/* 关联房间 */
function associationRoom(row) {
  if (row.lockType === 1) {
    // 公区锁
    accociation.value.isPublic = true
  } else {
    accociation.value.isPublic = false
  }
  
  handleGetAssociationList(row.lockId)
  // proxy.$refs['associationRoomRef'].show()
}

function unbindRoom(row) {
  LockApi.unBind(row.lockId).then(res => {
    proxy.$message.success('操作成功')
    accociation.value.visible = false
    accociation.value.data = []
    getList()
  })
}

function handleGetAssociationList(lockId) {
  LockApi.getList({lockId}).then(res => {
    const data = []
    res.rows.forEach(item => {
      if (item.roomId && item.roomId !== -1 && item.roomId !== '') {
        data.push(item)
      }
    })
    accociation.value.data = data
    accociation.value.total = data.length
    accociation.value.visible = true
  })
}

/* 详情页 */
function handleDetail(row) {
  router.push({ path: '/deviceManagement/smartLock/detail', query: {lockId: row.lockId}})
}

/* 开锁 */
function handleUnLock(row) {
  unlock(row.lockId).then(res => {
    proxy.$message.success('操作成功')
    getList()
  })
}

function getList() {
  list.value = []
  loading.value = true
  getLockList(queryParams.value).then((res) => {
    console.log(res)
    if (res.code === 200) {
      list.value = res.rows.map(it => {
        try {
          it.lockInfoObj = JSON.parse(it.lockInfo)
        } catch (e) {
          it.lockInfoObj = {}
        }
        return it
      })
      total.value = res.total
      loading.value = false
    }
  })
}
getList()
</script>
